﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.Console
{
    public static class Users
    {
        public static Adams.Admin.DataTransfer.Console.Users.PageLoad PageLoad()
        {
            var data = new Adams.Admin.DataTransfer.Console.Users.PageLoad();
            
            return data;
        }

        public static Adams.Admin.DataTransfer.Console.Users.GridLoad GridLoad(DataTransfer.GridLoadInput gridinput)
        {
            var data = new Adams.Admin.DataTransfer.Console.Users.GridLoad();
            data.Records = new Adams.Shared.Entities.Console.UserCollection();

            string filter = string.IsNullOrWhiteSpace(gridinput.Search) ? string.Empty : "FREETEXT ((FirstName,LastName,Email), '" + gridinput.Search.Replace("'", "''") + "' )";

            string dbq = DB.BuildPagingQuery(gridinput.StartRow, gridinput.PageSize,
                "*",
                "Console.Users",
                filter, string.Empty, gridinput.Sort + " " + gridinput.SortDirection, "UserID");

            using (SqlDataReader dr = DB.RunDataReader(dbq, CommandType.Text))
            {
                dr.Read();
                data.TotalRecords = dr[0].DbInt();

                dr.NextResult();
                while (dr.Read())
                {
                    var user = new Adams.Shared.Entities.Console.User();
                    user.ID = dr["UserID"].DbInt();
                    user.FirstName = dr["FirstName"].DbString();
                    user.LastName = dr["LastName"].DbString();
                    user.Email = dr["Email"].DbString();
                    user.IsActive = dr["IsActive"].DbBool();
                    user.IsLocked = dr["IsLocked"].DbBool();
                    data.Records.Add(user);
                }
            }

            return data;
        }

        public static void DeleteUser(int id)
        {
            DB.Run(@"
DELETE Console.UsersApplications WHERE UserID = @UserID
DELETE Console.Users WHERE UserID = @UserID
", CommandType.Text,
                    DB.CreateParameter("@UserID", id, SqlDbType.Int));
        }
    }
}
